<template>
  <!-- 增改用户弹框 -->
  <hcDialog
    dialogWidth="30%"
    :dialogTitle="options.type === 'add' ? '新增标签' : '编辑标签'"
    customClass="hymson-dialog mbb-dialog"
    :isVisable="options.show"
    @closeDialog="closeFun"
    @openDialog="openFun"
  >
    <el-form :rules="uprules" :model="upform" ref="upformRef" label-width="100">
      <el-form-item label="标签规范" prop="labelSpecCode">
        <el-input v-model="upform.labelSpecCode"></el-input>
      </el-form-item>
      <el-form-item label="模板文件">
        <el-upload
          ref="uploadRef"
          :on-change="handleChange"
          :auto-upload="false"
          :limit="1"
          class="upload-img"
        >
          <!-- <template #trigger> -->
          <el-button type="success" style="width: 100%"
            >选择标签模板文件</el-button
          >
          <!-- </template> -->
        </el-upload>
      </el-form-item>
      <el-form-item label="">
        <el-button @click="uploadFile" type="primary" :loading="uploading"
          >提 交</el-button
        >
      </el-form-item>
    </el-form>
  </hcDialog>
</template>

<script setup name="UserDialog">
import { reactive, ref } from "vue";
import { uploadImg } from "@/api/labels";

const emit = defineEmits(["closeDialog"]);

const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {
        show: false,
        type: "add", // 用于判断是编辑还是删除 add edit
        data: null, // 当前编辑的用户
      };
    },
  },
});
const upformRef = ref();
const uploadRef = ref();
let uploading = ref(false);
let upform = reactive({
  labelSpecCode: "",
  file: null,
});

const uprules = {
  labelSpecCode: [
    { required: true, message: "请输入标签规范", trigger: "blur" },
  ],
};

// 关闭弹框
const closeFun = () => {
  upformRef.value?.resetFields();
  upform.file = null;
  emit("closeDialog");
};

function openFun() {}

function handleChange(file) {
  let type = ["btw", "lab", "zpl"];
  let name = file.name.split(".");
  let ftype = name[name.length - 1];
  if (!type.includes(ftype.toLocaleLowerCase())) {
    uploadRef.value.clearFiles();
    ElMessage.error("请上传'btw,lab,zpl'格式模板文件");
    return false;
  }
  let filedata = new FormData();
  filedata.append("file", file.raw);
  upform.file = filedata;
}

async function uploadFile() {
  upformRef.value.validate(async (valid) => {
    if (valid) {
      try {
        uploading.value = true;
        let res = await uploadImg(upform.labelSpecCode, upform.file);
        uploading.value = false;
        if (res) {
          ElMessage.success("上传成功");
          emit("closeDialog", true);
        } else {
          ElMessage.error("上传失败");
        }
      } catch (e) {
        uploading.value = false;
        ElMessage.error("上传失败" + e);
      }
    }
  });
}
</script>

<style lang="scss" scoped>
.upload-img {
  width: 100%;
  .el-upload {
    width: 100% !important;
  }
}
</style>
